package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.pojos.dtos.HistorySearchDto;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    private MongoTemplate template;
    /**
     * 保存用户搜索条件
     * @param keyword
     * @param userId
     */
    @Override
    @Async
    public void insert(String keyword, Integer userId) {
        //查询当前用户的搜索关键字
        Query query=Query.query(Criteria.where("userId").is(userId).and("keyword")
        .is(keyword));
        ApUserSearch apUserSearch = template.findOne(query, ApUserSearch.class);
        //存在，更新时间
        if (apUserSearch!=null){
            apUserSearch.setCreatedTime(new Date());
            template.save(apUserSearch);
            return;
        }
        //不存在，判断当前历史记录是否超过10
        apUserSearch=new ApUserSearch();
        apUserSearch.setKeyword(keyword);
        apUserSearch.setUserId(userId);
        apUserSearch.setCreatedTime(new Date());
        Query query1=Query.query(Criteria.where("userId").is(userId));
        query1.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApUserSearch> apUserSearches = template.find(query1, ApUserSearch.class);
        //如果搜索记录小于10条 直接保存
        if (apUserSearches==null||apUserSearches.size()<10){
            template.save(apUserSearch);
        }else {
            //如果搜索记录大于等于10条，将最后一条剔除
            ApUserSearch lastApUserSearch = apUserSearches.get(apUserSearches.size() - 1);
            template.findAndReplace(Query
                    .query(Criteria.where("id").is(lastApUserSearch.getId())),apUserSearch);
        }
    }

    /**
     * 搜索历史记录
     * @return
     */
    @Override
    public ResponseResult findUserSearch() {
        //获得登录用户
        ApUser apUser = ApThreadLocalUtil.getApUser();
        if (apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //根据用户查询数据，按照时间倒序
        Query query=Query.query(Criteria.where("userId").is(apUser.getId()))
                .with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApUserSearch> apUserSearchList = template.find(query, ApUserSearch.class);
        return ResponseResult.okResult(apUserSearchList);
    }

    /**
     *删除搜索结果
     * @param dto
     * @return
     */
    @Override
    public ResponseResult deleteUserSearch(HistorySearchDto dto) {
        //检查参数
        if (dto==null||dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断是否登录
        ApUser apUser = ApThreadLocalUtil.getApUser();
        if (apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //删除
        Query query=Query.query(Criteria.where("userId").is(apUser.getId())
                .and("id").is(dto.getId()));
        template.remove(query,ApUserSearch.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
